package com.example.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * 监听过期事件
 *
 * @Author guoyb
 * @Date 2021/7/14  11:02
 */
@Configuration
public class RedisListenerConfig {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);


        //下面这种方式是灵活配置，针对每个库的失效key做处理,@后面参数为数据库序号, 即db0过期事件
        //也可以不加下面这一行,
        container.addMessageListener(new RedisKeyExpirationListener(), new PatternTopic("__keyevent@1__:expired"));
        return container;
    }
}
